package myJs

import myJs.Utils._
import myJs.myPkg._
import org.scalajs.dom.ext.Ajax
import myJs.myPkg.jquery._

import scala.scalajs.js
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import myJs.Implicits._
import org.scalajs.dom.{Element, document}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.scalajs.js.JSConverters._
import scala.scalajs.js.Dynamic.{global => g}

/**
 * Created by yz on 2019/4/15
 */
@JSExportTopLevel("RangeInfo")
object RangeInfo {

  @JSExport("init")
  def init = {
    refreshRangeInfo
    bootStrapValidator
    registerEvent
  }

  def registerEvent = {
    $(document.body).on("click", s".myUpdate", "", (y: Element) => {
      update
    })
  }

  def valueCheck={
    val formId="updateForm"
    val bv=$(s"#${formId}").bv
    var valid=true
    val altMin=$(s"#${formId}").findInputByName("altMin").myVal.toDouble
    val altMax=$(s"#${formId}").findInputByName("altMax").myVal.toDouble
    if(valid && altMin>altMax){
      bv.updateStatus("altMin", "INVALID", "blank")
      valid=false
    }
    val astMin=$(s"#${formId}").findInputByName("astMin").myVal.toDouble
    val astMax=$(s"#${formId}").findInputByName("astMax").myVal.toDouble
    if(valid && astMin>astMax){
      bv.updateStatus("astMin", "INVALID", "blank")
      valid=false
    }
    val pltMin=$(s"#${formId}").findInputByName("pltMin").myVal.toDouble
    val pltMax=$(s"#${formId}").findInputByName("pltMax").myVal.toDouble
    if(valid && astMin>astMax){
      bv.updateStatus("pltMin", "INVALID", "blank")
      valid=false
    }
    valid
  }

  def update = {
    val formId = "updateForm"
    val bv = $(s"#${formId}").bv
    bv.validate()
    val valid = bv.isValid()
    if (valid && valueCheck) {
      val data = $(s"#${formId}").serialize()
      val index = layer.alert(Tool.myElement, Tool.layerOptions)
      val url = g.jsRoutes.controllers.UserController.updateRange().url.toString
      Ajax.post(url = s"${url}", data = data, headers = Map("Content-Type" -> "application/x-www-form-urlencoded"),
        responseType = "application/json").map { xhr =>
        refreshRangeInfo.map{x=>
          layer.close(index)
          $("#modal").modal("hide")
          swal(SwalOptions(title = "成功", text = "修改成功!", `type` = "success"))
        }
      }
    }

  }

  def refreshRangeInfo = {
    val url = g.jsRoutes.controllers.UserController.getRangeInfo().url.toString
    Ajax.get(url = s"${url}", headers = Map("Content-Type" -> "application/json")).map { xhr =>
      val dict = xhr.responseText.toJDS
      val newDict = dict.map { case (k, v) =>
        val newV = if (v.isDouble) {
          doubleFormat(v)
        } else v
        (k, newV)
      }.toJSDictionary
      $("#ast").text(s"${newDict("astMin")} - ${newDict("astMax")}")
      $("#alt").text(s"${newDict("altMin")} - ${newDict("altMax")}")
      $("#plt").text(s"${newDict("pltMin")} - ${newDict("pltMax")}")
      Tool.fillByNames(newDict, "updateForm")
    }
  }

  def doubleFormat(v: String) = {
    if (v.toDouble.toInt == v.toDouble) {
      v.toDouble.toInt.toString
    } else v
  }

  def bootStrapValidator = {
    val url = g.jsRoutes.controllers.AdminController.userNameCheck().url.toString
    val dict = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> js.Dictionary(
        "astMin" -> {
          val info = "最小值"
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${info}不能为空！"
              ),
              "numeric" -> js.Dictionary(
                "message" -> s"${info}必须为数字",
              ),
              "between" -> js.Dictionary(
                "min" -> 0,
                "max" -> 1000,
                "message" ->  s"${info}必须处于0到1000之间！",
              ),
              "blank" -> js.Dictionary(
                "message"->"最小值不能大于最大值"
              )
            )
          )
        },
        "astMax" -> {
          val info = "最大值"
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${info}不能为空！"
              ),
              "numeric" -> js.Dictionary(
                "message" -> s"${info}必须为数字",
              ),
              "between" -> js.Dictionary(
                "min" -> 0,
                "max" -> 1000,
                "message" ->  s"${info}必须处于0到1000之间！",
              ),
              "blank" -> js.Dictionary()
            )
          )
        },
        "altMin" -> {
          val info = "最小值"
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${info}不能为空！"
              ),
              "numeric" -> js.Dictionary(
                "message" -> s"${info}必须为数字",
              ),
              "between" -> js.Dictionary(
                "min" -> 0,
                "max" -> 2000,
                "message" ->  s"${info}必须处于0到2000之间！",
              ),
              "blank" -> js.Dictionary(
                "message"->"最小值不能大于最大值"
              )
            )
          )
        },
        "pltMin" -> {
          val info = "最小值"
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${info}不能为空！"
              ),
              "numeric" -> js.Dictionary(
                "message" -> s"${info}必须为数字",
              ),
              "between" -> js.Dictionary(
                "min" -> 0,
                "max" -> 1000,
                "message" ->  s"${info}必须处于0到1000之间！",
              ),
              "blank" -> js.Dictionary(
                "message"->"最小值不能大于最大值"
              )
            )
          )
        },
        "altMax" -> {
          val info = "最大值"
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${info}不能为空！"
              ),
              "numeric" -> js.Dictionary(
                "message" -> s"${info}必须为数字",
              ),
              "between" -> js.Dictionary(
                "min" -> 0,
                "max" -> 2000,
                "message" ->  s"${info}必须处于0到2000之间！",
              ),
            )
          )
        },
        "pltMax" -> {
          val info = "最大值"
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${info}不能为空！"
              ),
              "numeric" -> js.Dictionary(
                "message" -> s"${info}必须为数字",
              ),
              "between" -> js.Dictionary(
                "min" -> 0,
                "max" -> 1000,
                "message" ->  s"${info}必须处于0到1000之间！",
              ),
            )
          )
        },
      )
    )
    g.$("#updateForm").bootstrapValidator(dict)
  }


}
